<?php

class SiteController extends Controller
{
	public function actionPaypalTest() {
	  $paypalManager = Yii::app()->getModule('SimplePaypal')->paypalManager;

	  $paypalManager->addField('item_name', 'Paypal Test Transaction');
	  $paypalManager->addField('amount', '0.01');
	  $paypalManager->addField('item_name_1', 'Test Title');
	  $paypalManager->addField('quantity_1', '2');
	  $paypalManager->addField('amount_1', '3');
	  $paypalManager->addField('custom', '111');

	  $paypalManager->dumpFields();   // for printing paypal form fields
	  //$paypalManager->submitPaypalPost();
	}

	public function actionConfirm() {
	  if (isset($_GET['q']) && 
	  	$_GET['q'] == 'success' && 
	  	(isset($_POST["txn_id"]) && isset($_POST["txn_type"]))
	  ) {

	      /* ToDo: code here after user return from paypal */

	  } else {
	      throw new CHttpException(404, 'The requested page does not exist.');
	  }
	}

	public function actionNotify() {
	  $logCat = 'paypal';
	  $paypalManager = Yii::app()->getModule('SimplePaypal')->paypalManager;
	  try {
	    if ($paypalManager->notify() && $_POST['payment_status'] === 'Completed') {
	      $model = new PaymentTransaction;
	      $model->user_id = $_POST['custom'];    // need to assign acutal user id
	      $model->mc_gross = $_POST['mc_gross'];
	      $model->payment_status = $_POST['payment_status'];
	      $model->payer_email = $_POST['payer_email'];
	      $model->verify_sign = $_POST['verify_sign'];
	      $model->txn_id = $_POST['txn_id'];
	      $model->payment_type = $_POST['payment_type'];
	      $model->receiver_email = $_POST['receiver_email'];
	      $model->txn_type = $_POST['txn_type'];
	      $model->item_name = $_POST['item_name'];
	      $model->ipn_track_id = $_POST['ipn_track_id'];
	      $model->save();

	      /* update user payement status field here */


	      Yii::log('ipn: ' . print_r($_POST, 1), CLogger::LEVEL_ERROR, $logCat);
	    } else {
	      Yii::log('invalid ipn', CLogger::LEVEL_ERROR, $logCat);
	    }
	  } catch (Exception $e) {
	    Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, $logCat);
	  }
	}

	public function actionCancel() {
	  /* ToDo: code here for paypal cancel */
	}
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionSearch($search = ''){
		if($search !== ''){
            $str = MyFunctionCustom::remove_accents($search);
            $str_return = strtolower($str);
			$criteria = new CDbCriteria;
			$criteria->select = '*';
			$criteria->condition = '(street like "%' . $str_return .'%"' .
								   ' OR city like "%' . $str_return .'%"'.
								   ' OR state like "%' . $str_return .'%"'.
								   ' OR zip like "%'. $str_return .'%")';
									//' AND end_date >='. time();
			$result = Post::model()->findAll($criteria);
			//echo "<pre>";print_r($result);die;
			$this->render('search', compact(array('result','search')));
		}else{
			$this->render('search');
		}
	}

	public function actionPost(){
		$model = new Post();
		if(isset($_POST['title']) &&
		   isset($_POST['content']) &&
		   isset($_POST['other_address']) &&
		   isset($_POST['start_date']) &&
		   isset($_POST['end_date']) &&
		   isset($_POST['time']) &&
		   isset($_FILES['photo']) &&
		   isset(Yii::app()->session['_LOGGED_USER'])){
		   	$user = Yii::app()->session['_LOGGED_USER'];
		   	if(is_uploaded_file($_FILES['photo']['tmp_name'])) {
				$sourcePath = $_FILES['photo']['tmp_name'];
				$ran = rand(0, 999999999);
				$fileName = trim(date('Y-m-d H-i-s') . $ran) . '.' . $_FILES['photo']['name'];
				$targetPath = Yii::app()->basePath . "/../images/post/". $fileName;
				$model = new Post();
				$model->title = $_POST['title'];
				$model->description = $_POST['content'];
				$model->start_date = $_POST['start_date'];
				$model->end_date = $_POST['end_date'];
				$model->timer = $_POST['time'];
				$model->created_date = time();
				$model->cover_photo = $fileName;
				$model->user_id = $user['id'];
				$model->lat = $_POST['lat'];
				$model->lng = $_POST['lng'];
				$model->zip = $_POST['zip'];
				$model->city = $_POST['city'];
				$model->street = $_POST['other_address'];
				if($_FILES['photo']['size'] < 1048567){
					if(move_uploaded_file($sourcePath, $targetPath) && $model->save()) {
						echo CJSON::encode(1);
					}
					elseif ($_FILES["photo"]["error"] > 0){
				   		echo CJSON::encode(0);
				   	}
				}else{
					echo CJSON::encode(2);
				}
			}else{
				echo CJSON::encode(3);
			}
		}
		//$this->render('post', compact('model'));
	}
	public function actionAroud(){
		if(isset($_GET['lat']) && isset($_GET['lng']) && isset($_GET["radius"])){
			$center_lat = $_GET["lat"];
			$center_lng = $_GET["lng"];
			$radius = $_GET["radius"];

			// Start XML file, create parent node
			$dom = new DOMDocument("1.0");
			$node = $dom->createElement("markers");
			$parnode = $dom->appendChild($node);

			// Opens a connection to a mySQL server
			$criteria = new CDbCriteria;
			$criteria->select = "title, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance";
			//$criteria->condition = '';

			//$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
		  	// mysql_real_escape_string($center_lat),
		  	// mysql_real_escape_string($center_lng),
		  	// mysql_real_escape_string($center_lat),
		  	//mysql_real_escape_string($radius));
			//$result = mysql_query($query);
			$data = Post::model()->findAll($criteria);
			header("Content-type: text/xml");
			foreach ($data as $dt){
			  $node = $dom->createElement("marker");
			  $newnode = $parnode->appendChild($node);
			  $newnode->setAttribute("title", $dt['title']);
			  //$newnode->setAttribute("address", $dt['address']);
			  $newnode->setAttribute("lat", $dt['lat']);
			  $newnode->setAttribute("lng", $dt['lng']);
			  //11$newnode->setAttribute("distance", $dt['distance']);
			}
			echo $dom->saveXML();
			// $latN = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(0))));
	  //       $latS = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(180))));
	  //       $lonE = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(90)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));
	  //       $lonW = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(270)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));
		}
	}
	public function actionIndex()
	{
		$seller = Benefit::model()->getAllByType(1);
		$buyer = Benefit::model()->getAllByType(2);
		$criteria = new CDbCriteria;
		$criteria->order = 'created_date DESC';
		$criteria->limit = 1;
		$feedback = Feedback::model()->find($criteria);
		$this->render('index', compact(array('seller', 'buyer', 'feedback')));
	}

	public function actionFeedback(){
		if(isset(Yii::app()->session['_LOGGED_USER']) && isset($_POST['content'])){
			$user = Yii::app()->session['_LOGGED_USER'];
			$feedback = new Feedback;
			$feedback->user_id = $user['id'];
			$feedback->created_date = time();
			$feedback->content = $_POST['content'];
			if($feedback->save()){
				$this->redirect('/');
			}else{
				var_dump($feedback);
			}
		}else{
			$this->redirect('/');
		}
	}

	public function actionMaps(){
		if(isset($_POST['minLat'],
			$_POST['maxLat'], $_POST['minLng'], $_POST['maxLng'])){
	    	$criteria = new CDbCriteria;
	    	$criteria->condition = ('lat >=:minLat AND lat <=:maxLat AND lng >=:minLng AND lng <=:maxLng');
	    	$criteria->params = array(':minLat' => $_POST['minLat'], ':maxLat' => $_POST['maxLat'],
	    								':minLng' => $_POST['minLng'], ':maxLng' => $_POST['maxLng']);
	    	$criteria->order = 'created_date DESC';
			$model = Post::model()->findAll($criteria);
			$stationList = array();
			foreach ($model as $key => $value){			
				$a = [
						'latlng' => [$value['lat'], $value['lng']],
						'title' => $value['title'],
						'photo' => $value['cover_photo'],
						'address' => $value['street'] .', '. $value['city'].', '. $value['state'],
						'date' => $value['timer'],
						'description'=> $value['description']
				];
				array_push($stationList, $a);
				Yii::app()->session['_newlist'] = count($stationList);
			}
			echo CJSON::encode($stationList);
		}
	}

	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	public function actionContact(){
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	public function actionLogin(){
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	public function actionLogout(){
		if(isset(Yii::app()->session['_LOGGED_USER'])){
			//Yii::app()->user->logout();
			unset(Yii::app()->session['_LOGGED_USER']);
		}
		$this->redirect(Yii::app()->homeUrl);
	}
}